<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>

	
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
		<meta http-equiv="Content-Language" content="en-us">

		<title>Django | Django&amp;#8217;s cache framework | Django Documentation</title>

		<meta name="ROBOTS" content="ALL">
		<meta http-equiv="imagetoolbar" content="no">
		<meta name="MSSmartTagsPreventParsing" content="true">
		<meta name="Copyright" content="This site's design and contents Copyright (c) 2005  Lawrence Journal-World.">

		<meta name="keywords" content="Python, Django, framework, open-source">
		<meta name="description" content="Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.">

		<link href="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/base.css" rel="stylesheet" type="text/css" media="screen">
		<link href="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/print.css" rel="stylesheet" type="text/css" media="print">
      
  
  <style type="text/css" media="screen">
    #docs-search {
      color: #000;
      float: right;
    }
    #docs-search form {
      font-size: 92%;
      margin: 0;
      padding: 1em 1em 0;
      white-space: nowrap;
    }
    form.search ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    form.search li {
      display: inline;
      padding-right: 1em;
    }
    form.search .query {
      width: 18em;
    }
  </style>
  <link rel="stylesheet" href="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/pygments.css" type="text/css">

	</head><body id="documentation" class="default">

	<div id="container">
		<div id="header">
			<h1 id="logo"><a href="http://www.djangoproject.com/"><img src="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/hdr_logo.gif" alt="Django"></a></h1>
			<ul id="nav-global">
				<li id="nav-homepage"><a href="http://www.djangoproject.com/">Home</a></li>
				<li id="nav-download"><a href="http://www.djangoproject.com/download/">Download</a></li>
				<li id="nav-documentation"><a href="http://docs.djangoproject.com/">Documentation</a></li>
				<li id="nav-weblog"><a href="http://www.djangoproject.com/weblog/">Weblog</a></li>
				<li id="nav-community"><a href="http://www.djangoproject.com/community/">Community</a></li>
				<li id="nav-code"><a href="http://code.djangoproject.com/">Code</a></li>
			</ul>
		</div>
		<!-- END Header -->
		<div id="billboard">
  <h2><a href="http://docs.djangoproject.com/en/1.0/">Django documentation</a></h2>
</div>
		<div id="columnwrap">
			
		<div id="content-main">
		


  <h2 class="deck">
  
    This document describes Django version 1.0. For development documentation, 
    <a href="http://docs.djangoproject.com/en/dev/topics/cache/">go here</a>.
  
  </h2>
  <div class="section" id="s-django-s-cache-framework">
<span id="s-topics-cache"></span><span id="django-s-cache-framework"></span><span id="topics-cache"></span><h1>Django’s cache framework<a class="headerlink" href="#django-s-cache-framework" title="Permalink to this headline">¶</a></h1>
<p>A fundamental trade-off in dynamic Web sites is, well, they’re dynamic. Each
time a user requests a page, the Web server makes all sorts of calculations –
from database queries to template rendering to business logic – to create the
page that your site’s visitor sees. This is a lot more expensive, from a
processing-overhead perspective, than your standard
read-a-file-off-the-filesystem server arrangement.</p>
<p>For most Web applications, this overhead isn’t a big deal. Most Web
applications aren’t washingtonpost.com or slashdot.org; they’re simply small-
to medium-sized sites with so-so traffic. But for medium- to high-traffic
sites, it’s essential to cut as much overhead as possible.</p>
<p>That’s where caching comes in.</p>
<p>To cache something is to save the result of an expensive calculation so that
you don’t have to perform the calculation next time. Here’s some pseudocode
explaining how this would work for a dynamically generated Web page:</p>
<div class="highlight-python"><pre>given a URL, try finding that page in the cache
if the page is in the cache:
    return the cached page
else:
    generate the page
    save the generated page in the cache (for next time)
    return the generated page</pre>
</div>
<p>Django comes with a robust cache system that lets you save dynamic pages so
they don't have to be calculated for each request. For convenience, Django
offers different levels of cache granularity: You can cache the output of
specific views, you can cache only the pieces that are difficult to produce, or
you can cache your entire site.</p>
<p>Django also works well with "upstream" caches, such as Squid
(<a class="reference external" href="http://www.squid-cache.org/">http://www.squid-cache.org/</a>) and browser-based caches. These are the types of
caches that you don't directly control but to which you can provide hints (via
HTTP headers) about which parts of your site should be cached, and how.</p>
<div class="section" id="s-setting-up-the-cache">
<span id="setting-up-the-cache"></span><h2>Setting up the cache<a class="headerlink" href="#setting-up-the-cache" title="Permalink to this headline">¶</a></h2>
<p>The cache system requires a small amount of setup. Namely, you have to tell it
where your cached data should live -- whether in a database, on the filesystem
or directly in memory. This is an important decision that affects your cache's
performance; yes, some cache types are faster than others.</p>
<p>Your cache preference goes in the <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> setting in your settings
file. Here's an explanation of all available values for <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt>.</p>
<div class="section" id="s-memcached">
<span id="memcached"></span><h3>Memcached<a class="headerlink" href="#memcached" title="Permalink to this headline">¶</a></h3>
<p>By far the fastest, most efficient type of cache available to Django, Memcached
is an entirely memory-based cache framework originally developed to handle high
loads at LiveJournal.com and subsequently open-sourced by Danga Interactive.
It's used by sites such as Facebook and Wikipedia to reduce database access and
dramatically increase site performance.</p>
<p>Memcached is available for free at <a class="reference external" href="http://danga.com/memcached/">http://danga.com/memcached/</a> . It runs as a
daemon and is allotted a specified amount of RAM. All it does is provide an
fast interface for adding, retrieving and deleting arbitrary data in the cache.
All data is stored directly in memory, so there's no overhead of database or
filesystem usage.</p>
<p>After installing Memcached itself, you'll need to install the Memcached Python
bindings, which are not bundled with Django directly. Two versions of this are
available. Choose and install <em>one</em> of the following modules:</p>
<ul class="simple">
<li>The fastest available option is a module called <tt class="docutils literal"><span class="pre">cmemcache</span></tt>, available
at <a class="reference external" href="http://gijsbert.org/cmemcache/">http://gijsbert.org/cmemcache/</a> .</li>
<li>If you can't install <tt class="docutils literal"><span class="pre">cmemcache</span></tt>, you can install <tt class="docutils literal"><span class="pre">python-memcached</span></tt>,
available at <a class="reference external" href="ftp://ftp.tummy.com/pub/python-memcached/">ftp://ftp.tummy.com/pub/python-memcached/</a> . If that URL is
no longer valid, just go to the Memcached Web site
(<a class="reference external" href="http://www.danga.com/memcached/">http://www.danga.com/memcached/</a>) and get the Python bindings from the
"Client APIs" section.</li>
</ul>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> The <tt class="docutils literal"><span class="pre">cmemcache</span></tt> option is new in 1.0. Previously, only
<tt class="docutils literal"><span class="pre">python-memcached</span></tt> was supported.</div>
<p>To use Memcached with Django, set <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> to
<tt class="docutils literal"><span class="pre">memcached://ip:port/</span></tt>, where <tt class="docutils literal"><span class="pre">ip</span></tt> is the IP address of the Memcached
daemon and <tt class="docutils literal"><span class="pre">port</span></tt> is the port on which Memcached is running.</p>
<p>In this example, Memcached is running on localhost (127.0.0.1) port 11211:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'memcached://127.0.0.1:11211/'</span>
</pre></div>
</div>
<p>One excellent feature of Memcached is its ability to share cache over multiple
servers. This means you can run Memcached daemons on multiple machines, and the
program will treat the group of machines as a <em>single</em> cache, without the need
to duplicate cache values on each machine. To take advantage of this feature,
include all server addresses in <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt>, separated by semicolons.</p>
<p>In this example, the cache is shared over Memcached instances running on IP
address 172.19.26.240 and 172.19.26.242, both on port 11211:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'memcached://172.19.26.240:11211;172.19.26.242:11211/'</span>
</pre></div>
</div>
<p>In the following example, the cache is shared over Memcached instances running
on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
172.19.26.244 (port 11213):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'memcached://172.19.26.240:11211;172.19.26.242:11212;172.19.26.244:11213/'</span>
</pre></div>
</div>
<p>A final point about Memcached is that memory-based caching has one
disadvantage: Because the cached data is stored in memory, the data will be
lost if your server crashes. Clearly, memory isn't intended for permanent data
storage, so don't rely on memory-based caching as your only data storage.
Without a doubt, <em>none</em> of the Django caching backends should be used for
permanent storage -- they're all intended to be solutions for caching, not
storage -- but we point this out here because memory-based caching is
particularly temporary.</p>
</div>
<div class="section" id="s-database-caching">
<span id="database-caching"></span><h3>Database caching<a class="headerlink" href="#database-caching" title="Permalink to this headline">¶</a></h3>
<p>To use a database table as your cache backend, first create a cache table in
your database by running this command:</p>
<div class="highlight-python"><pre>python manage.py createcachetable [cache_table_name]</pre>
</div>
<p>...where <tt class="docutils literal"><span class="pre">[cache_table_name]</span></tt> is the name of the database table to create.
(This name can be whatever you want, as long as it's a valid table name that's
not already being used in your database.) This command creates a single table
in your database that is in the proper format that Django's database-cache
system expects.</p>
<p>Once you've created that database table, set your <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> setting to
<tt class="docutils literal"><span class="pre">"db://tablename"</span></tt>, where <tt class="docutils literal"><span class="pre">tablename</span></tt> is the name of the database table.
In this example, the cache table's name is <tt class="docutils literal"><span class="pre">my_cache_table</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'db://my_cache_table'</span>
</pre></div>
</div>
<p>The database caching backend uses the same database as specified in your
settings file. You can't use a different database backend for your cache table.</p>
<p>Database caching works best if you've got a fast, well-indexed database server.</p>
</div>
<div class="section" id="s-filesystem-caching">
<span id="filesystem-caching"></span><h3>Filesystem caching<a class="headerlink" href="#filesystem-caching" title="Permalink to this headline">¶</a></h3>
<p>To store cached items on a filesystem, use the <tt class="docutils literal"><span class="pre">"file://"</span></tt> cache type for
<tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt>. For example, to store cached data in <tt class="docutils literal"><span class="pre">/var/tmp/django_cache</span></tt>,
use this setting:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'file:///var/tmp/django_cache'</span>
</pre></div>
</div>
<p>Note that there are three forward slashes toward the beginning of that example.
The first two are for <tt class="docutils literal"><span class="pre">file://</span></tt>, and the third is the first character of the
directory path, <tt class="docutils literal"><span class="pre">/var/tmp/django_cache</span></tt>. If you're on Windows, put the
drive letter after the <tt class="docutils literal"><span class="pre">file://</span></tt>, like this:</p>
<div class="highlight-python"><pre>file://c:/foo/bar</pre>
</div>
<p>The directory path should be absolute -- that is, it should start at the root
of your filesystem. It doesn't matter whether you put a slash at the end of the
setting.</p>
<p>Make sure the directory pointed-to by this setting exists and is readable and
writable by the system user under which your Web server runs. Continuing the
above example, if your server runs as the user <tt class="docutils literal"><span class="pre">apache</span></tt>, make sure the
directory <tt class="docutils literal"><span class="pre">/var/tmp/django_cache</span></tt> exists and is readable and writable by the
user <tt class="docutils literal"><span class="pre">apache</span></tt>.</p>
<p>Each cache value will be stored as a separate file whose contents are the
cache data saved in a serialized ("pickled") format, using Python's <tt class="docutils literal"><span class="pre">pickle</span></tt>
module. Each file's name is the cache key, escaped for safe filesystem use.</p>
</div>
<div class="section" id="s-local-memory-caching">
<span id="local-memory-caching"></span><h3>Local-memory caching<a class="headerlink" href="#local-memory-caching" title="Permalink to this headline">¶</a></h3>
<p>If you want the speed advantages of in-memory caching but don't have the
capability of running Memcached, consider the local-memory cache backend. This
cache is multi-process and thread-safe. To use it, set <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> to
<tt class="docutils literal"><span class="pre">"locmem:///"</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'locmem:///'</span>
</pre></div>
</div>
<p>Note that each process will have its own private cache instance, which means no
cross-process caching is possible. This obviously also means the local memory
cache isn't particularly memory-efficient, so it's probably not a good choice
for production environments. It's nice for development.</p>
</div>
<div class="section" id="s-dummy-caching-for-development">
<span id="dummy-caching-for-development"></span><h3>Dummy caching (for development)<a class="headerlink" href="#dummy-caching-for-development" title="Permalink to this headline">¶</a></h3>
<p>Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
just implements the cache interface without doing anything.</p>
<p>This is useful if you have a production site that uses heavy-duty caching in
various places but a development/test environment where you don't want to cache
and don't want to have to change your code to special-case the latter. To
activate dummy caching, set <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'dummy:///'</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-a-custom-cache-backend">
<span id="using-a-custom-cache-backend"></span><h3>Using a custom cache backend<a class="headerlink" href="#using-a-custom-cache-backend" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>While Django includes support for a number of cache backends out-of-the-box,
sometimes you might want to use a customized cache backend. To use an external
cache backend with Django, use a Python import path as the scheme portion (the
part before the initial colon) of the <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> URI, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">'path.to.backend://'</span>
</pre></div>
</div>
<p>If you're building your own backend, you can use the standard cache backends
as reference implementations. You'll find the code in the
<tt class="docutils literal"><span class="pre">django/core/cache/backends/</span></tt> directory of the Django source.</p>
<p>Note: Without a really compelling reason, such as a host that doesn't support
them, you should stick to the cache backends included with Django. They've
been well-tested and are easy to use.</p>
</div>
<div class="section" id="s-cache-backend-arguments">
<span id="cache-backend-arguments"></span><h3>CACHE_BACKEND arguments<a class="headerlink" href="#cache-backend-arguments" title="Permalink to this headline">¶</a></h3>
<p>Each cache backend may take arguments. They're given in query-string style on
the <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> setting. Valid arguments are as follows:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">timeout</span></tt>: The default timeout, in seconds, to use for the cache.
This argument defaults to 300 seconds (5 minutes).</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">max_entries</span></tt>: For the <tt class="docutils literal"><span class="pre">locmem</span></tt>, <tt class="docutils literal"><span class="pre">filesystem</span></tt> and <tt class="docutils literal"><span class="pre">database</span></tt>
backends, the maximum number of entries allowed in the cache before old
values are deleted. This argument defaults to 300.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">cull_frequency</span></tt>: The fraction of entries that are culled when
<tt class="docutils literal"><span class="pre">max_entries</span></tt> is reached. The actual ratio is <tt class="docutils literal"><span class="pre">1/cull_frequency</span></tt>, so
set <tt class="docutils literal"><span class="pre">cull_frequency=2</span></tt> to cull half of the entries when <tt class="docutils literal"><span class="pre">max_entries</span></tt>
is reached.</p>
<p>A value of <tt class="docutils literal"><span class="pre">0</span></tt> for <tt class="docutils literal"><span class="pre">cull_frequency</span></tt> means that the entire cache will
be dumped when <tt class="docutils literal"><span class="pre">max_entries</span></tt> is reached. This makes culling <em>much</em>
faster at the expense of more cache misses.</p>
</li>
</ul>
<p>In this example, <tt class="docutils literal"><span class="pre">timeout</span></tt> is set to <tt class="docutils literal"><span class="pre">60</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">"memcached://127.0.0.1:11211/?timeout=60"</span>
</pre></div>
</div>
<p>In this example, <tt class="docutils literal"><span class="pre">timeout</span></tt> is <tt class="docutils literal"><span class="pre">30</span></tt> and <tt class="docutils literal"><span class="pre">max_entries</span></tt> is <tt class="docutils literal"><span class="pre">400</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CACHE_BACKEND</span> <span class="o">=</span> <span class="s">"locmem:///?timeout=30&amp;max_entries=400"</span>
</pre></div>
</div>
<p>Invalid arguments are silently ignored, as are invalid values of known
arguments.</p>
</div>
</div>
<div class="section" id="s-the-per-site-cache">
<span id="the-per-site-cache"></span><h2>The per-site cache<a class="headerlink" href="#the-per-site-cache" title="Permalink to this headline">¶</a></h2>
<div class="versionchanged">
<span class="title">Changed in Django 1.0:</span> (previous versions of Django only provided a single <tt class="docutils literal"><span class="pre">CacheMiddleware</span></tt> instead
of the two pieces described below).</div>
<p>Once the cache is set up, the simplest way to use caching is to cache your
entire site. You'll need to add
<tt class="docutils literal"><span class="pre">'django.middleware.cache.UpdateCacheMiddleware'</span></tt> and
<tt class="docutils literal"><span class="pre">'django.middleware.cache.FetchFromCacheMiddleware'</span></tt> to your
<tt class="docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt> setting, as in this example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">MIDDLEWARE_CLASSES</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s">'django.middleware.cache.UpdateCacheMiddleware'</span><span class="p">,</span>
    <span class="s">'django.middleware.common.CommonMiddleware'</span><span class="p">,</span>
    <span class="s">'django.middleware.cache.FetchFromCacheMiddleware'</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">No, that's not a typo: the "update" middleware must be first in the list,
and the "fetch" middleware must be last. The details are a bit obscure, but
see <a class="reference internal" href="#order-of-middleware-classes">Order of MIDDLEWARE_CLASSES</a> below if you'd like the full story.</p>
</div>
<p>Then, add the following required settings to your Django settings file:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></tt> -- The number of seconds each page should be
cached.</li>
<li><tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_KEY_PREFIX</span></tt> -- If the cache is shared across multiple
sites using the same Django installation, set this to the name of the site,
or some other string that is unique to this Django instance, to prevent key
collisions. Use an empty string if you don't care.</li>
</ul>
<p>The cache middleware caches every page that doesn't have GET or POST
parameters. Optionally, if the <tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_ANONYMOUS_ONLY</span></tt> setting is
<tt class="xref docutils literal"><span class="pre">True</span></tt>, only anonymous requests (i.e., not those made by a logged-in user)
will be cached. This is a simple and effective way of disabling caching for any
user-specific pages (include Django's admin interface). Note that if you use
<tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_ANONYMOUS_ONLY</span></tt>, you should make sure you've activated
<tt class="docutils literal"><span class="pre">AuthenticationMiddleware</span></tt>.</p>
<p>Additionally, the cache middleware automatically sets a few headers in each
<tt class="docutils literal"><span class="pre">HttpResponse</span></tt>:</p>
<ul class="simple">
<li>Sets the <tt class="docutils literal"><span class="pre">Last-Modified</span></tt> header to the current date/time when a fresh
(uncached) version of the page is requested.</li>
<li>Sets the <tt class="docutils literal"><span class="pre">Expires</span></tt> header to the current date/time plus the defined
<tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></tt>.</li>
<li>Sets the <tt class="docutils literal"><span class="pre">Cache-Control</span></tt> header to give a max age for the page --
again, from the <tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></tt> setting.</li>
</ul>
<p>See <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/http/middleware/#topics-http-middleware"><em>Middleware</em></a> for more on middleware.</p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If a view sets its own cache expiry time (i.e. it has a <tt class="docutils literal"><span class="pre">max-age</span></tt> section in
its <tt class="docutils literal"><span class="pre">Cache-Control</span></tt> header) then the page will be cached until the expiry
time, rather than <tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></tt>. Using the decorators in
<tt class="docutils literal"><span class="pre">django.views.decorators.cache</span></tt> you can easily set a view's expiry time
(using the <tt class="docutils literal"><span class="pre">cache_control</span></tt> decorator) or disable caching for a view (using
the <tt class="docutils literal"><span class="pre">never_cache</span></tt> decorator). See the <a class="reference internal" href="#controlling-cache-using-other-headers">using other headers</a> section for
more on these decorators.</p>
</div>
<div class="section" id="s-the-per-view-cache">
<span id="the-per-view-cache"></span><h2>The per-view cache<a class="headerlink" href="#the-per-view-cache" title="Permalink to this headline">¶</a></h2>
<p>A more granular way to use the caching framework is by caching the output of
individual views. <tt class="docutils literal"><span class="pre">django.views.decorators.cache</span></tt> defines a <tt class="docutils literal"><span class="pre">cache_page</span></tt>
decorator that will automatically cache the view's response for you. It's easy
to use:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.views.decorators.cache</span> <span class="k">import</span> <span class="n">cache_page</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>

<span class="n">my_view</span> <span class="o">=</span> <span class="n">cache_page</span><span class="p">(</span><span class="n">my_view</span><span class="p">,</span> <span class="mf">60</span> <span class="o">*</span> <span class="mf">15</span><span class="p">)</span>
</pre></div>
</div>
<p>Or, using Python 2.4's decorator syntax:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@cache_page</span><span class="p">(</span><span class="mf">60</span> <span class="o">*</span> <span class="mf">15</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">cache_page</span></tt> takes a single argument: the cache timeout, in seconds. In the
above example, the result of the <tt class="docutils literal"><span class="pre">my_view()</span></tt> view will be cached for 15
minutes. (Note that we've written it as <tt class="docutils literal"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></tt> for the purpose of
readability. <tt class="docutils literal"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></tt> will be evaluated to <tt class="docutils literal"><span class="pre">900</span></tt> -- that is, 15 minutes
multiplied by 60 seconds per minute.)</p>
<p>The per-view cache, like the per-site cache, is keyed off of the URL. If
multiple URLs point at the same view, each URL will be cached separately.
Continuing the <tt class="docutils literal"><span class="pre">my_view</span></tt> example, if your URLconf looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">(</span><span class="s">''</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r'^foo/(\d{1,2})/$'</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>then requests to <tt class="docutils literal"><span class="pre">/foo/1/</span></tt> and <tt class="docutils literal"><span class="pre">/foo/23/</span></tt> will be cached separately, as
you may expect. But once a particular URL (e.g., <tt class="docutils literal"><span class="pre">/foo/23/</span></tt>) has been
requested, subsequent requests to that URL will use the cache.</p>
<div class="section" id="s-specifying-per-view-cache-in-the-urlconf">
<span id="specifying-per-view-cache-in-the-urlconf"></span><h3>Specifying per-view cache in the URLconf<a class="headerlink" href="#specifying-per-view-cache-in-the-urlconf" title="Permalink to this headline">¶</a></h3>
<p>The examples in the previous section have hard-coded the fact that the view is
cached, because <tt class="docutils literal"><span class="pre">cache_page</span></tt> alters the <tt class="docutils literal"><span class="pre">my_view</span></tt> function in place. This
approach couples your view to the cache system, which is not ideal for several
reasons. For instance, you might want to reuse the view functions on another,
cache-less site, or you might want to distribute the views to people who might
want to use them without being cached. The solution to these problems is to
specify the per-view cache in the URLconf rather than next to the view functions
themselves.</p>
<p>Doing so is easy: simply wrap the view function with <tt class="docutils literal"><span class="pre">cache_page</span></tt> when you
refer to it in the URLconf. Here's the old URLconf from earlier:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">(</span><span class="s">''</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r'^foo/(\d{1,2})/$'</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Here's the same thing, with <tt class="docutils literal"><span class="pre">my_view</span></tt> wrapped in <tt class="docutils literal"><span class="pre">cache_page</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.views.decorators.cache</span> <span class="k">import</span> <span class="n">cache_page</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">(</span><span class="s">''</span><span class="p">,</span>
    <span class="p">(</span><span class="s">r'^foo/(\d{1,2})/$'</span><span class="p">,</span> <span class="n">cache_page</span><span class="p">(</span><span class="n">my_view</span><span class="p">,</span> <span class="mf">60</span> <span class="o">*</span> <span class="mf">15</span><span class="p">)),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>If you take this approach, don't forget to import <tt class="docutils literal"><span class="pre">cache_page</span></tt> within your
URLconf.</p>
</div>
</div>
<div class="section" id="s-template-fragment-caching">
<span id="template-fragment-caching"></span><h2>Template fragment caching<a class="headerlink" href="#template-fragment-caching" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If you're after even more control, you can also cache template fragments using
the <tt class="docutils literal"><span class="pre">cache</span></tt> template tag. To give your template access to this tag, put
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">cache</span> <span class="pre">%}</span></tt> near the top of your template.</p>
<p>The <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></tt> template tag caches the contents of the block for a given
amount of time. It takes at least two arguments: the cache timeout, in seconds,
and the name to give the cache fragment. For example:</p>
<div class="highlight-python"><pre>{% load cache %}
{% cache 500 sidebar %}
    .. sidebar ..
{% endcache %}</pre>
</div>
<p>Sometimes you might want to cache multiple copies of a fragment depending on
some dynamic data that appears inside the fragment. For example, you might want a
separate cached copy of the sidebar used in the previous example for every user
of your site. Do this by passing additional arguments to the <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></tt>
template tag to uniquely identify the cache fragment:</p>
<div class="highlight-python"><pre>{% load cache %}
{% cache 500 sidebar request.user.username %}
    .. sidebar for logged in user ..
{% endcache %}</pre>
</div>
<p>It's perfectly fine to specify more than one argument to identify the fragment.
Simply pass as many arguments to <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></tt> as you need.</p>
<p>The cache timeout can be a template variable, as long as the template variable
resolves to an integer value. For example, if the template variable
<tt class="docutils literal"><span class="pre">my_timeout</span></tt> is set to the value <tt class="docutils literal"><span class="pre">600</span></tt>, then the following two examples are
equivalent:</p>
<div class="highlight-python"><pre>{% cache 600 sidebar %} ... {% endcache %}
{% cache my_timeout sidebar %} ... {% endcache %}</pre>
</div>
<p>This feature is useful in avoiding repetition in templates. You can set the
timeout in a variable, in one place, and just reuse that value.</p>
</div>
<div class="section" id="s-the-low-level-cache-api">
<span id="the-low-level-cache-api"></span><h2>The low-level cache API<a class="headerlink" href="#the-low-level-cache-api" title="Permalink to this headline">¶</a></h2>
<p>Sometimes, caching an entire rendered page doesn't gain you very much and is,
in fact, inconvenient overkill.</p>
<p>Perhaps, for instance, your site includes a view whose results depend on
several expensive queries, the results of which change at different intervals.
In this case, it would not be ideal to use the full-page caching that the
per-site or per-view cache strategies offer, because you wouldn't want to
cache the entire result (since some of the data changes often), but you'd still
want to cache the results that rarely change.</p>
<p>For cases like this, Django exposes a simple, low-level cache API. You can use
this API to store objects in the cache with any level of granularity you like.
You can cache any Python object that can be pickled safely: strings,
dictionaries, lists of model objects, and so forth. (Most common Python objects
can be pickled; refer to the Python documentation for more information about
pickling.)</p>
<p>The cache module, <tt class="docutils literal"><span class="pre">django.core.cache</span></tt>, has a <tt class="docutils literal"><span class="pre">cache</span></tt> object that's
automatically created from the <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> setting:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">from</span> <span class="nn">django.core.cache</span> <span class="k">import</span> <span class="n">cache</span>
</pre></div>
</div>
<p>The basic interface is <tt class="docutils literal"><span class="pre">set(key,</span> <span class="pre">value,</span> <span class="pre">timeout_seconds)</span></tt> and <tt class="docutils literal"><span class="pre">get(key)</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'my_key'</span><span class="p">,</span> <span class="s">'hello, world!'</span><span class="p">,</span> <span class="mf">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'my_key'</span><span class="p">)</span>
<span class="go">'hello, world!'</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">timeout_seconds</span></tt> argument is optional and defaults to the <tt class="docutils literal"><span class="pre">timeout</span></tt>
argument in the <tt class="docutils literal"><span class="pre">CACHE_BACKEND</span></tt> setting (explained above).</p>
<p>If the object doesn't exist in the cache, <tt class="docutils literal"><span class="pre">cache.get()</span></tt> returns <tt class="xref docutils literal"><span class="pre">None</span></tt>:</p>
<div class="highlight-python"><pre># Wait 30 seconds for 'my_key' to expire...

&gt;&gt;&gt; cache.get('my_key')
None</pre>
</div>
<p>We advise against storing the literal value <tt class="xref docutils literal"><span class="pre">None</span></tt> in the cache, because you
won't be able to distinguish between your stored <tt class="xref docutils literal"><span class="pre">None</span></tt> value and a cache
miss signified by a return value of <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">cache.get()</span></tt> can take a <tt class="docutils literal"><span class="pre">default</span></tt> argument. This specifies which value to
return if the object doesn't exist in the cache:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'my_key'</span><span class="p">,</span> <span class="s">'has expired'</span><span class="p">)</span>
<span class="go">'has expired'</span>
</pre></div>
</div>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>To add a key only if it doesn't already exist, use the <tt class="docutils literal"><span class="pre">add()</span></tt> method.
It takes the same parameters as <tt class="docutils literal"><span class="pre">set()</span></tt>, but it will not attempt to
update the cache if the key specified is already present:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'add_key'</span><span class="p">,</span> <span class="s">'Initial value'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s">'add_key'</span><span class="p">,</span> <span class="s">'New value'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'add_key'</span><span class="p">)</span>
<span class="go">'Initial value'</span>
</pre></div>
</div>
<p>If you need to know whether <tt class="docutils literal"><span class="pre">add()</span></tt> stored a value in the cache, you can
check the return value. It will return <tt class="xref docutils literal"><span class="pre">True</span></tt> if the value was stored,
<tt class="xref docutils literal"><span class="pre">False</span></tt> otherwise.</p>
<p>There's also a <tt class="docutils literal"><span class="pre">get_many()</span></tt> interface that only hits the cache once.
<tt class="docutils literal"><span class="pre">get_many()</span></tt> returns a dictionary with all the keys you asked for that
actually exist in the cache (and haven't expired):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'a'</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'b'</span><span class="p">,</span> <span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'c'</span><span class="p">,</span> <span class="mf">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_many</span><span class="p">([</span><span class="s">'a'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">,</span> <span class="s">'c'</span><span class="p">])</span>
<span class="go">{'a': 1, 'b': 2, 'c': 3}</span>
</pre></div>
</div>
<p>Finally, you can delete keys explicitly with <tt class="docutils literal"><span class="pre">delete()</span></tt>. This is an easy way
of clearing the cache for a particular object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s">'a'</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<span class="title">New in Django 1.1:</span> <div class="system-message">
<p class="system-message-title">System Message: WARNING/2 (<tt class="docutils">/home/djangodocs/en/1.0/topics/cache.txt</tt>)</p>
undefined label: releases-1.1</div>
</div>
<p>You can also increment or decrement a key that already exists using the
<tt class="docutils literal"><span class="pre">incr()</span></tt> or <tt class="docutils literal"><span class="pre">decr()</span></tt> methods, respectively. By default, the existing cache
value will incremented or decremented by 1. Other increment/decrement values
can be specified by providing an argument to the increment/decrement call. A
ValueError will be raised if you attempt to increment or decrement a
nonexistent cache key.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'num'</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s">'num'</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s">'num'</span><span class="p">,</span> <span class="mf">10</span><span class="p">)</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s">'num'</span><span class="p">)</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s">'num'</span><span class="p">,</span> <span class="mf">5</span><span class="p">)</span>
<span class="go">6</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><tt class="docutils literal"><span class="pre">incr()</span></tt>/<tt class="docutils literal"><span class="pre">decr()</span></tt> methods are not guaranteed to be atomic. On those
backends that support atomic increment/decrement (most notably, the
memcached backend), increment and decrement operations will be atomic.
However, if the backend doesn't natively provide an increment/decrement
operation, it will be implemented using a two-step retrieve/update.</p>
</div>
</div>
<div class="section" id="s-upstream-caches">
<span id="upstream-caches"></span><h2>Upstream caches<a class="headerlink" href="#upstream-caches" title="Permalink to this headline">¶</a></h2>
<p>So far, this document has focused on caching your <em>own</em> data. But another type
of caching is relevant to Web development, too: caching performed by "upstream"
caches. These are systems that cache pages for users even before the request
reaches your Web site.</p>
<p>Here are a few examples of upstream caches:</p>
<ul class="simple">
<li>Your ISP may cache certain pages, so if you requested a page from
<a class="reference external" href="http://example.com/">http://example.com/</a>, your ISP would send you the page without having to
access example.com directly. The maintainers of example.com have no
knowledge of this caching; the ISP sits between example.com and your Web
browser, handling all of the caching transparently.</li>
<li>Your Django Web site may sit behind a <em>proxy cache</em>, such as Squid Web
Proxy Cache (<a class="reference external" href="http://www.squid-cache.org/">http://www.squid-cache.org/</a>), that caches pages for
performance. In this case, each request first would be handled by the
proxy, and it would be passed to your application only if needed.</li>
<li>Your Web browser caches pages, too. If a Web page sends out the
appropriate headers, your browser will use the local cached copy for
subsequent requests to that page, without even contacting the Web page
again to see whether it has changed.</li>
</ul>
<p>Upstream caching is a nice efficiency boost, but there's a danger to it:
Many Web pages' contents differ based on authentication and a host of other
variables, and cache systems that blindly save pages based purely on URLs could
expose incorrect or sensitive data to subsequent visitors to those pages.</p>
<p>For example, say you operate a Web e-mail system, and the contents of the
"inbox" page obviously depend on which user is logged in. If an ISP blindly
cached your site, then the first user who logged in through that ISP would have
his user-specific inbox page cached for subsequent visitors to the site. That's
not cool.</p>
<p>Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
exist to instruct upstream caches to differ their cache contents depending on
designated variables, and to tell caching mechanisms not to cache particular
pages. We'll look at some of these headers in the sections that follow.</p>
</div>
<div class="section" id="s-using-vary-headers">
<span id="using-vary-headers"></span><h2>Using Vary headers<a class="headerlink" href="#using-vary-headers" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">Vary</span></tt> header defines which request headers a cache
mechanism should take into account when building its cache key. For example, if
the contents of a Web page depend on a user's language preference, the page is
said to "vary on language."</p>
<p>By default, Django's cache system creates its cache keys using the requested
path (e.g., <tt class="docutils literal"><span class="pre">"/stories/2005/jun/23/bank_robbed/"</span></tt>). This means every request
to that URL will use the same cached version, regardless of user-agent
differences such as cookies or language preferences. However, if this page
produces different content based on some difference in request headers -- such
as a cookie, or a language, or a user-agent -- you'll need to use the <tt class="docutils literal"><span class="pre">Vary</span></tt>
header to tell caching mechanisms that the page output depends on those things.</p>
<p>To do this in Django, use the convenient <tt class="docutils literal"><span class="pre">vary_on_headers</span></tt> view decorator,
like so:</p>
<div class="highlight-python"><pre>from django.views.decorators.vary import vary_on_headers

# Python 2.3 syntax.
def my_view(request):
    # ...
my_view = vary_on_headers(my_view, 'User-Agent')

# Python 2.4+ decorator syntax.
@vary_on_headers('User-Agent')
def my_view(request):
    # ...</pre>
</div>
<p>In this case, a caching mechanism (such as Django's own cache middleware) will
cache a separate version of the page for each unique user-agent.</p>
<p>The advantage to using the <tt class="docutils literal"><span class="pre">vary_on_headers</span></tt> decorator rather than manually
setting the <tt class="docutils literal"><span class="pre">Vary</span></tt> header (using something like
<tt class="docutils literal"><span class="pre">response['Vary']</span> <span class="pre">=</span> <span class="pre">'user-agent'</span></tt>) is that the decorator <em>adds</em> to the
<tt class="docutils literal"><span class="pre">Vary</span></tt> header (which may already exist), rather than setting it from scratch
and potentially overriding anything that was already in there.</p>
<p>You can pass multiple headers to <tt class="docutils literal"><span class="pre">vary_on_headers()</span></tt>:</p>
<div class="highlight-python"><pre>@vary_on_headers('User-Agent', 'Cookie')
def my_view(request):
    # ...</pre>
</div>
<p>This tells upstream caches to vary on <em>both</em>, which means each combination of
user-agent and cookie will get its own cache value. For example, a request with
the user-agent <tt class="docutils literal"><span class="pre">Mozilla</span></tt> and the cookie value <tt class="docutils literal"><span class="pre">foo=bar</span></tt> will be considered
different from a request with the user-agent <tt class="docutils literal"><span class="pre">Mozilla</span></tt> and the cookie value
<tt class="docutils literal"><span class="pre">foo=ham</span></tt>.</p>
<p>Because varying on cookie is so common, there's a <tt class="docutils literal"><span class="pre">vary_on_cookie</span></tt>
decorator. These two views are equivalent:</p>
<div class="highlight-python"><pre>@vary_on_cookie
def my_view(request):
    # ...

@vary_on_headers('Cookie')
def my_view(request):
    # ...</pre>
</div>
<p>The headers you pass to <tt class="docutils literal"><span class="pre">vary_on_headers</span></tt> are not case sensitive;
<tt class="docutils literal"><span class="pre">"User-Agent"</span></tt> is the same thing as <tt class="docutils literal"><span class="pre">"user-agent"</span></tt>.</p>
<p>You can also use a helper function, <tt class="docutils literal"><span class="pre">django.utils.cache.patch_vary_headers</span></tt>,
directly. This function sets, or adds to, the <tt class="docutils literal"><span class="pre">Vary</span> <span class="pre">header</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.utils.cache</span> <span class="k">import</span> <span class="n">patch_vary_headers</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">'template_name'</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
    <span class="n">patch_vary_headers</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="p">[</span><span class="s">'Cookie'</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">patch_vary_headers</span></tt> takes an <tt class="docutils literal"><span class="pre">HttpResponse</span></tt> instance as its first argument
and a list/tuple of case-insensitive header names as its second argument.</p>
<p>For more on Vary headers, see the <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44">official Vary spec</a>.</p>
</div>
<div class="section" id="s-controlling-cache-using-other-headers">
<span id="controlling-cache-using-other-headers"></span><h2>Controlling cache: Using other headers<a class="headerlink" href="#controlling-cache-using-other-headers" title="Permalink to this headline">¶</a></h2>
<p>Other problems with caching are the privacy of data and the question of where
data should be stored in a cascade of caches.</p>
<p>A user usually faces two kinds of caches: his or her own browser cache (a
private cache) and his or her provider's cache (a public cache). A public cache
is used by multiple users and controlled by someone else. This poses problems
with sensitive data--you don't want, say, your bank account number stored in a
public cache. So Web applications need a way to tell caches which data is
private and which is public.</p>
<p>The solution is to indicate a page's cache should be "private." To do this in
Django, use the <tt class="docutils literal"><span class="pre">cache_control</span></tt> view decorator. Example:</p>
<div class="highlight-python"><pre>from django.views.decorators.cache import cache_control

@cache_control(private=True)
def my_view(request):
    # ...</pre>
</div>
<p>This decorator takes care of sending out the appropriate HTTP header behind the
scenes.</p>
<p>There are a few other ways to control cache parameters. For example, HTTP
allows applications to do the following:</p>
<ul class="simple">
<li>Define the maximum time a page should be cached.</li>
<li>Specify whether a cache should always check for newer versions, only
delivering the cached content when there are no changes. (Some caches
might deliver cached content even if the server page changed, simply
because the cache copy isn't yet expired.)</li>
</ul>
<p>In Django, use the <tt class="docutils literal"><span class="pre">cache_control</span></tt> view decorator to specify these cache
parameters. In this example, <tt class="docutils literal"><span class="pre">cache_control</span></tt> tells caches to revalidate the
cache on every access and to store cached versions for, at most, 3,600 seconds:</p>
<div class="highlight-python"><pre>from django.views.decorators.cache import cache_control

@cache_control(must_revalidate=True, max_age=3600)
def my_view(request):
    # ...</pre>
</div>
<p>Any valid <tt class="docutils literal"><span class="pre">Cache-Control</span></tt> HTTP directive is valid in <tt class="docutils literal"><span class="pre">cache_control()</span></tt>.
Here's a full list:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">public=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">private=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">no_cache=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">no_transform=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">must_revalidate=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">proxy_revalidate=True</span></tt></li>
<li><tt class="docutils literal"><span class="pre">max_age=num_seconds</span></tt></li>
<li><tt class="docutils literal"><span class="pre">s_maxage=num_seconds</span></tt></li>
</ul>
<p>For explanation of Cache-Control HTTP directives, see the <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9">Cache-Control spec</a>.</p>
<p>(Note that the caching middleware already sets the cache header's max-age with
the value of the <tt class="docutils literal"><span class="pre">CACHE_MIDDLEWARE_SETTINGS</span></tt> setting. If you use a custom
<tt class="docutils literal"><span class="pre">max_age</span></tt> in a <tt class="docutils literal"><span class="pre">cache_control</span></tt> decorator, the decorator will take
precedence, and the header values will be merged correctly.)</p>
<p>If you want to use headers to disable caching altogether,
<tt class="docutils literal"><span class="pre">django.views.decorators.cache.never_cache</span></tt> is a view decorator that adds
headers to ensure the response won't be cached by browsers or other caches.
Example:</p>
<div class="highlight-python"><pre>from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
    # ...</pre>
</div>
</div>
<div class="section" id="s-other-optimizations">
<span id="other-optimizations"></span><h2>Other optimizations<a class="headerlink" href="#other-optimizations" title="Permalink to this headline">¶</a></h2>
<p>Django comes with a few other pieces of middleware that can help optimize your
apps' performance:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">django.middleware.http.ConditionalGetMiddleware</span></tt> adds support for
modern browsers to conditionally GET responses based on the <tt class="docutils literal"><span class="pre">ETag</span></tt>
and <tt class="docutils literal"><span class="pre">Last-Modified</span></tt> headers.</li>
<li><tt class="docutils literal"><span class="pre">django.middleware.gzip.GZipMiddleware</span></tt> compresses responses for all
moderns browsers, saving bandwidth and transfer time.</li>
</ul>
</div>
<div class="section" id="s-order-of-middleware-classes">
<span id="order-of-middleware-classes"></span><h2>Order of MIDDLEWARE_CLASSES<a class="headerlink" href="#order-of-middleware-classes" title="Permalink to this headline">¶</a></h2>
<p>If you use caching middleware, it's important to put each half in the right
place within the <tt class="docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt> setting. That's because the cache
middleware needs to know which headers by which to vary the cache storage.
Middleware always adds something to the <tt class="docutils literal"><span class="pre">Vary</span></tt> response header when it can.</p>
<p><tt class="docutils literal"><span class="pre">UpdateCacheMiddleware</span></tt> runs during the response phase, where middleware is
run in reverse order, so an item at the top of the list runs <em>last</em> during the
response phase. Thus, you need to make sure that <tt class="docutils literal"><span class="pre">UpdateCacheMiddleware</span></tt>
appears <em>before</em> any other middleware that might add something to the <tt class="docutils literal"><span class="pre">Vary</span></tt>
header. The following middleware modules do so:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> adds <tt class="docutils literal"><span class="pre">Cookie</span></tt></li>
<li><tt class="docutils literal"><span class="pre">GZipMiddleware</span></tt> adds <tt class="docutils literal"><span class="pre">Accept-Encoding</span></tt></li>
<li><tt class="docutils literal"><span class="pre">LocaleMiddleware</span></tt> adds <tt class="docutils literal"><span class="pre">Accept-Language</span></tt></li>
</ul>
<p><tt class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></tt>, on the other hand, runs during the request phase,
where middleware is applied first-to-last, so an item at the top of the list
runs <em>first</em> during the request phase. The <tt class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></tt> also
needs to run after other middleware updates the <tt class="docutils literal"><span class="pre">Vary</span></tt> header, so
<tt class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></tt> must be <em>after</em> any item that does so.</p>
</div>
</div>



<div id="content-secondary">
  <h2 id="comments">Questions/Feedback</h2>
  <p>Having trouble? We'd like to help!</p>
  <ul>
    <li>
      Try the <a href="http://docs.djangoproject.com/en/dev/faq/">FAQ</a> — it's got answers to many common
      questions.
    </li>
    <li>
      Search for information in the <a href="http://groups.google.com/group/django-users/">archives of the
      django-users mailing list</a>, or <a href="http://groups.google.com/group/django-users/">post a question</a>.
    </li>
    <li>
      Ask a question in the <a href="irc://irc.freenode.net/">#django IRC
      channel</a>, or search the <a href="http://oebfare.com/logger/django/">IRC
      logs</a> to see if its been asked before.
    </li>
    <li>
      If you notice errors with this documentation, please <a href="http://code.djangoproject.com/simpleticket?component=Documentation">
      open a ticket</a> and let us know! Please only use the ticket tracker for
      criticisms and improvements on the docs. For tech support, use the
      resources above.
    </li>
  </ul>
</div>

		</div>
		<!-- END #content-main -->
		<div id="content-related" class="sidebar">
		
  
    <h2>Contents</h2>
    
      <ul>
<li><a class="reference external" href="">Django’s cache framework</a><ul>
<li><a class="reference external" href="#setting-up-the-cache">Setting up the cache</a><ul>
<li><a class="reference external" href="#memcached">Memcached</a></li>
<li><a class="reference external" href="#database-caching">Database caching</a></li>
<li><a class="reference external" href="#filesystem-caching">Filesystem caching</a></li>
<li><a class="reference external" href="#local-memory-caching">Local-memory caching</a></li>
<li><a class="reference external" href="#dummy-caching-for-development">Dummy caching (for development)</a></li>
<li><a class="reference external" href="#using-a-custom-cache-backend">Using a custom cache backend</a></li>
<li><a class="reference external" href="#cache-backend-arguments">CACHE_BACKEND arguments</a></li>
</ul>
</li>
<li><a class="reference external" href="#the-per-site-cache">The per-site cache</a></li>
<li><a class="reference external" href="#the-per-view-cache">The per-view cache</a><ul>
<li><a class="reference external" href="#specifying-per-view-cache-in-the-urlconf">Specifying per-view cache in the URLconf</a></li>
</ul>
</li>
<li><a class="reference external" href="#template-fragment-caching">Template fragment caching</a></li>
<li><a class="reference external" href="#the-low-level-cache-api">The low-level cache API</a></li>
<li><a class="reference external" href="#upstream-caches">Upstream caches</a></li>
<li><a class="reference external" href="#using-vary-headers">Using Vary headers</a></li>
<li><a class="reference external" href="#controlling-cache-using-other-headers">Controlling cache: Using other headers</a></li>
<li><a class="reference external" href="#other-optimizations">Other optimizations</a></li>
<li><a class="reference external" href="#order-of-middleware-classes">Order of MIDDLEWARE_CLASSES</a></li>
</ul>
</li>
</ul>

    
  
  
  
    <h2>Search</h2>
    
    <form action="/en/1.0/search/" id="search" class="search">
  <div>
    <input name="cx" value="009763561546736975936:e88ek0eurf4" type="hidden">
    <input name="cof" value="FORID:11" type="hidden">
    <input name="ie" value="UTF-8" type="hidden">
    <input name="hl" value="" type="hidden">
    <input style="background: rgb(255, 255, 255) url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" id="id_search_q" class="query" name="q" type="text">
    <input name="sa" class="submit" value="Search" type="submit">
    <ul>
<li><label for="id_search_as_q_0"><input checked="checked" id="id_search_as_q_0" value="more:dev_docs" name="as_q" type="radio"> Latest</label></li>
<li><label for="id_search_as_q_1"><input id="id_search_as_q_1" value="more:1.0_docs" name="as_q" type="radio"> 1.0</label></li>
<li><label for="id_search_as_q_2"><input id="id_search_as_q_2" value="more:0.96_docs" name="as_q" type="radio"> 0.96</label></li>
<li><label for="id_search_as_q_3"><input id="id_search_as_q_3" value="more:all_docs" name="as_q" type="radio"> All</label></li>
</ul>
  </div>
</form>
<script type="text/javascript" src="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/brand.html"></script>
  
  
  
    <h2>Browse</h2>
    <ul>
      
        
          <li>Prev: <a href="http://docs.djangoproject.com/en/1.0/topics/auth/">User authentication in Django</a></li>
        
        
          <li>Next: <a href="http://docs.djangoproject.com/en/1.0/topics/email/">Sending e-mail</a></li>
        
        <li><a href="http://docs.djangoproject.com/en/1.0/contents/">Table of contents</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/genindex/">General Index</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/modindex/">Global Module Index</a></li>
        
      
    </ul>
  
  
  
    <h2>You are here:</h2>
    <ul>
      
        <li>
          <a href="http://docs.djangoproject.com/en/1.0/">Django 1.0 documentation</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/">Using Django</a>
          
          <ul><li>Django’s cache framework</li></ul>
          </li></ul>
        </li>
      
    </ul>
  
  
  
    <h3>Last update:</h3>
    <div>May 23, 2009, 8:15 a.m. (<a href="http://www.timeanddate.com/worldclock/city.html?n=64">CDT</a>)</div>
  

		</div>
		<!-- END #content-related -->

		</div>
		<!-- END #content -->
		<div id="footer">
			<p>© 2005-2009 <a href="http://www.djangoproject.com/foundation/">Django Software Foundation</a> unless otherwise noted. Django is a registered trademark of the Django Software Foundation. 
			Hosting graciously provided by <a href="http://mediatemple.net/">
			<img style="vertical-align: middle; position: relative; top: -1px;" src="Django%20%7C%20Django&amp;%238217;s%20cache%20framework%20%7C%20Django%20Documentation_files/mt.png" alt="media temple"></a>
			</p>
		</div>
		<!-- END #footer -->
	</div>
	<!-- END #container -->
	</body></html>